import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import api from '../services/api'

export const useDeployStore = defineStore('deploy', () => {
  // 部署状态
  const deployStatus = ref({
    isDeploying: false,
    currentDeployId: null,
    status: 'idle', // idle, deploying, success, failed
    progress: 0,
    message: '',
    startTime: null,
    endTime: null
  })

  // 当前部署详情
  const currentDeployment = ref(null)

  // 统计信息
  const stats = ref({
    total: 0,
    success: 0,
    failed: 0,
    successRate: 0
  })

  // 历史记录
  const history = ref([])
  const historyPagination = ref({
    current: 1,
    pageSize: 10,
    total: 0
  })

  // 配置信息
  const config = ref({})

  // 加载状态
  const loading = ref({
    stats: false,
    history: false,
    config: false,
    deploy: false,
    logs: false
  })

  // 日志信息
  const logs = ref([])

  // 计算属性
  const isDeploying = computed(() => deployStatus.value.isDeploying)
  const hasCurrentDeployment = computed(() => !!currentDeployment.value)

  // 统计信息方法
  const loadStats = async () => {
    try {
      loading.value.stats = true
      const response = await api.getStats()
      if (response.success) {
        stats.value = response.data
      }
      return response
    } catch (error) {
      console.error('加载统计信息失败:', error)
      throw error
    } finally {
      loading.value.stats = false
    }
  }

  // 部署管理方法
  const getCurrentDeployStatus = async () => {
    try {
      const response = await api.getCurrentDeployStatus()
      if (response.success) {
        const data = response.data
        deployStatus.value = {
          isDeploying: data.status === 'deploying',
          currentDeployId: data.deployId,
          status: data.status,
          progress: data.progress || 0,
          message: data.message || '',
          startTime: data.startTime,
          endTime: data.endTime
        }
      }
      return response
    } catch (error) {
      console.error('获取当前部署状态失败:', error)
      throw error
    }
  }

  const getDeployStatus = async (deployId) => {
    try {
      const response = await api.getDeployStatus(deployId)
      if (response.success) {
        currentDeployment.value = response.data
      }
      return response
    } catch (error) {
      console.error('获取部署状态失败:', error)
      throw error
    }
  }

  const manualDeploy = async (params = {}) => {
    try {
      loading.value.deploy = true
      const response = await api.manualDeploy(params)
      if (response.success) {
        deployStatus.value.isDeploying = true
        deployStatus.value.currentDeployId = response.data.deployId
        deployStatus.value.status = 'deploying'
        deployStatus.value.startTime = new Date().toISOString()
        
        // 刷新统计信息
        await loadStats()
      }
      return response
    } catch (error) {
      console.error('手动部署失败:', error)
      throw error
    } finally {
      loading.value.deploy = false
    }
  }

  const stopDeploy = async () => {
    try {
      const response = await api.stopDeploy()
      if (response.success) {
        deployStatus.value.isDeploying = false
        deployStatus.value.status = 'stopped'
        deployStatus.value.endTime = new Date().toISOString()
      }
      return response
    } catch (error) {
      console.error('停止部署失败:', error)
      throw error
    }
  }

  const getDeployLogs = async (deployId) => {
    try {
      loading.value.logs = true
      const response = await api.getDeployLogs(deployId)
      if (response.success) {
        logs.value = response.data.logs || []
      }
      return response
    } catch (error) {
      console.error('获取部署日志失败:', error)
      throw error
    } finally {
      loading.value.logs = false
    }
  }

  // 历史记录方法
  const loadHistory = async (params = {}) => {
    try {
      loading.value.history = true
      const response = await api.getHistory(params)
      if (response.success) {
        history.value = response.data.records || []
        historyPagination.value = {
          current: response.data.pagination?.page || 1,
          pageSize: response.data.pagination?.limit || 10,
          total: response.data.pagination?.total || 0
        }
      }
      return response
    } catch (error) {
      console.error('加载历史记录失败:', error)
      throw error
    } finally {
      loading.value.history = false
    }
  }

  const getHistoryById = async (deployId) => {
    try {
      const response = await api.getHistoryById(deployId)
      return response
    } catch (error) {
      console.error('获取历史记录详情失败:', error)
      throw error
    }
  }

  const deleteHistory = async (deployId) => {
    try {
      const response = await api.deleteHistory(deployId)
      if (response.success) {
        // 刷新历史记录和统计信息
        await Promise.all([
          loadHistory({ 
            page: historyPagination.value.current, 
            limit: historyPagination.value.pageSize 
          }),
          loadStats()
        ])
      }
      return response
    } catch (error) {
      console.error('删除历史记录失败:', error)
      throw error
    }
  }

  const batchDeleteHistory = async (deployIds) => {
    try {
      const response = await api.batchDeleteHistory(deployIds)
      if (response.success) {
        // 刷新历史记录和统计信息
        await Promise.all([
          loadHistory({ 
            page: historyPagination.value.current, 
            limit: historyPagination.value.pageSize 
          }),
          loadStats()
        ])
      }
      return response
    } catch (error) {
      console.error('批量删除历史记录失败:', error)
      throw error
    }
  }

  const clearHistory = async () => {
    try {
      const response = await api.clearHistory()
      if (response.success) {
        history.value = []
        historyPagination.value.total = 0
        await loadStats()
      }
      return response
    } catch (error) {
      console.error('清空历史记录失败:', error)
      throw error
    }
  }

  // 配置管理方法
  const loadConfig = async () => {
    try {
      loading.value.config = true
      const response = await api.getConfig()
      if (response.success) {
        config.value = response.data
      }
      return response
    } catch (error) {
      console.error('加载配置失败:', error)
      throw error
    } finally {
      loading.value.config = false
    }
  }

  const updateConfig = async (newConfig) => {
    try {
      const response = await api.updateConfig(newConfig)
      if (response.success) {
        config.value = { ...config.value, ...newConfig }
      }
      return response
    } catch (error) {
      console.error('更新配置失败:', error)
      throw error
    }
  }

  const resetConfig = async () => {
    try {
      const response = await api.resetConfig()
      if (response.success) {
        await loadConfig()
      }
      return response
    } catch (error) {
      console.error('重置配置失败:', error)
      throw error
    }
  }

  const validateConfig = async (configData) => {
    try {
      const response = await api.validateConfig(configData)
      return response
    } catch (error) {
      console.error('验证配置失败:', error)
      throw error
    }
  }

  const validateAuthConfig = async (authConfig) => {
    try {
      const response = await api.validateAuthConfig(authConfig)
      return response
    } catch (error) {
      console.error('验证认证配置失败:', error)
      throw error
    }
  }

  // 重置所有状态
  const resetState = () => {
    deployStatus.value = {
      isDeploying: false,
      currentDeployId: null,
      status: 'idle',
      progress: 0,
      message: '',
      startTime: null,
      endTime: null
    }
    currentDeployment.value = null
    stats.value = {
      total: 0,
      success: 0,
      failed: 0,
      successRate: 0
    }
    history.value = []
    historyPagination.value = {
      current: 1,
      pageSize: 10,
      total: 0
    }
    config.value = {}
    logs.value = []
  }

  return {
    // 状态
    deployStatus,
    currentDeployment,
    stats,
    history,
    historyPagination,
    config,
    loading,
    logs,
    
    // 计算属性
    isDeploying,
    hasCurrentDeployment,
    
    // 统计信息方法
    loadStats,
    
    // 部署管理方法
    getCurrentDeployStatus,
    getDeployStatus,
    manualDeploy,
    stopDeploy,
    getDeployLogs,
    
    // 历史记录方法
    loadHistory,
    getHistoryById,
    deleteHistory,
    batchDeleteHistory,
    clearHistory,
    
    // 配置管理方法
    loadConfig,
    updateConfig,
    resetConfig,
    validateConfig,
    validateAuthConfig,
    
    // 工具方法
    resetState
  }
})